package com.lib.search;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.lib.model.encryptedIndex;
import com.lib.model.fileScorePair;


public class searchModule {
	/**
	 * 
	 * @param indexMap
	 * @param trapDoor
	 * @return
	 */
	public static List<fileScorePair>getRelvlentFileInfo(Map<String, encryptedIndex> indexMap,encryptedIndex trapDoor)
	{
		long startTime=System.currentTimeMillis();
		List<fileScorePair>resultList=new ArrayList<fileScorePair>();
		Set<String> keySet=indexMap.keySet();
		Iterator<String>iterator=keySet.iterator();
		double score=0;
		while(iterator.hasNext())
		{
			String fileName=iterator.next();
			encryptedIndex enIndex=indexMap.get(fileName);
			score=getScore(enIndex, trapDoor);
			if(score>1E-6)
			{
				resultList.add(new fileScorePair(fileName,score));
			}
		}
		long endTime=System.currentTimeMillis();
		System.out.println("计算所有文件的相关分数时间是："+(endTime-startTime)+"ms'");
		return resultList;
	}
	/**
	 * 
	 * @param fileScorePairs
	 * @param k
	 * @return
	 */
	public static List<String> getMostRelateFile(List<fileScorePair>fileScorePairs,int k)
	{
		List<String>fileList=new ArrayList<String>();
		for(int i=1;i<fileScorePairs.size();i++)
		{
			fileScorePair key=fileScorePairs.get(i);
			int j=i-1;
			while(j>=0&&fileScorePairs.get(j).getScore()<key.getScore())
			{
				fileScorePairs.set(j+1, fileScorePairs.get(j));
				j=j-1;
			}
			fileScorePairs.set(j+1, key);
		}
		if(fileScorePairs.size()<=k)
		{
			for(int i=0;i<fileScorePairs.size();i++)
			{
				fileList.add(fileScorePairs.get(i).getFileName());
			}
		}
		else {
			for(int i=0;i<k;i++)
			{
				fileList.add(fileScorePairs.get(i).getFileName());
			}
		}
		return fileList;
	}
	/**
	 *
	 * @param enIndex
	 * @param trap
	 * @return
	 */
	public static double getScore(encryptedIndex enIndex,encryptedIndex trap)
	{
		double[] MD1=enIndex.getMD1();
		double[] MD2=enIndex.getMD2();
		double[] MQ1=trap.getMD1();
		double[] MQ2=trap.getMD2();
		double score=0;
		for(int i=0;i<MD1.length;i++)
		{
			double tempScore=MD1[i]*MQ1[i]+MD2[i]*MQ2[i];
			score+=tempScore;
		}
		return score;
	
	}

}
